package com.example.lecturereservation.controller;

import com.example.lecturereservation.entity.Admin;
import com.example.lecturereservation.service.AdminService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;
import java.util.logging.Logger;

@Controller
public class AdminController {

    @Autowired
    AdminService adminService;

    //日志
    java.util.logging.Logger logger = Logger.getLogger(this.getClass().getName());

    //注册功能
    @RequestMapping("/adminlogin")
    @ResponseBody
    public String adminlogin(@RequestBody Map<String, String> maps, HttpServletRequest request) {

        logger.info("用户开始登录了...");

        String email = maps.get("email");
        String password = maps.get("password");

        logger.info("登录邮箱：" + email);
        logger.info("登录密码：" + password);

        if (email.length() == 0) return "请输入邮箱！";
        Admin admin = this.adminService.findByEmail(email);
        if (admin == null) return "邮箱不存在";
        if (!admin.getPassword().equals(password)) return "密码错误";

        //网站使用会话技术（每个用户拥有自己的会话）记住用户.30分钟
        request.getSession().setAttribute("admin", admin);

        logger.info("用户登录成功！");

        return "ok";
    }

    //获取已登录用户
    @RequestMapping("/getLoginAdmin")
    @ResponseBody
    public Admin getLoginAdmin(HttpServletRequest request) {
        //通过session获取登录的用户
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        admin.setPassword("********");
        //判断用户是否登录
        if (admin == null) {
            logger.info("用户未登录，非法请求！");
            admin = new Admin();
            admin.setId(-1);
            return admin;
        }
        return admin;
    }

    //退出登录
    @RequestMapping("/adminunlogin")
    @ResponseBody
    public String adminunlogin(HttpServletRequest request) {
        request.getSession().setAttribute("admin", null);
        return "ok";
    }

    @RequestMapping("/adminregistration")
    @ResponseBody
    public String adminregistration(@RequestBody Map<String, String> maps) {

        logger.info("开始注册...");

        //获取参数
        String email = maps.get("email");
        String password = maps.get("password");
        String name = maps.get("name");
        Integer telephone = Integer.valueOf(maps.get("telephone"));


        //创建用户
        Admin admin = new Admin();
        admin.setEmail(email);
        admin.setPassword(password);
        admin.setName(name);
        admin.setTelephone(telephone);


        //注册用户
        return this.adminService.registration(admin);
    }
}